import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../utils/http.dart';

const key = '45f53b9fdc6a031b5d0a5a9149dcfae2';
const baseUrl = 'https://restapi.amap.com/v3';

class Location extends StatefulWidget {
  const Location({super.key});

  @override
  State<Location> createState() => _LocationState();
}

class _LocationState extends State<Location> {
  bool isLoading = false;
  String address = '点击获取位置';
  double longitude = 0;
  double latitude = 0;
  List nearbyCommunities = [];

  @override
  void initState() {
    super.initState();
    doAsyncInit();
  }

  Future<void> doAsyncInit() async {
    try {
      bool isGranted = await requestLocationPermission();
      if (!isGranted) {
        ToastUtils.error('位置权限未授予, 请去设置中心开启');
        return;
      }
      await getLocation();
      await reverseGeocoding(longitude, latitude);
      await queryNearbyCommunities(longitude, latitude);
      // await Future.wait([
      //   reverseGeocoding(116.350077, 40.065956),
      //   queryNearbyCommunities(116.350077, 40.065956),
      // ]);
    } catch (e) {
      print(e);
    }
  }

  /// 请求位置权限
  Future<bool> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    return status.isGranted;
  }

  /// 获取当前位置经纬度
  Future<void> getLocation() async {
    late LocationSettings locationSettings;
    if (defaultTargetPlatform == TargetPlatform.android) {
      // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
      locationSettings = AndroidSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        forceLocationManager: true,
        intervalDuration: const Duration(seconds: 10),
        foregroundNotificationConfig: const ForegroundNotificationConfig(
          notificationText:
              "Example app will continue to receive your location even when you aren't using it",
          notificationTitle: "Running in Background",
          enableWakeLock: true,
        ),
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // 只有在应用在后台启动时才设置为true
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      // 对于其他平台，默认设置高精度定位和100米距离过滤
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }
    try {
      setState(() {
        isLoading = true;
        address = '正在定位中...';
      });
      // 获取当前位置
      var location = await Geolocator.getCurrentPosition(
        locationSettings: locationSettings,
      );
      longitude = location.longitude;
      latitude = location.latitude;
      // reverseGeocoding(location.longitude, location.latitude);
    } catch (e) {
      print(e);
      setState(() {
        isLoading = false;
        address = '无法获取当前位置';
      });
    }
  }

  /// 逆地址解析
  Future<void> reverseGeocoding(double longitude, double latitude) async {
    try {
      final res = await http.get(
        '$baseUrl/geocode/regeo?key=$key&location=$longitude,$latitude',
        returnFullResponse: true,
      );
      if (res['status'] == '1') {
        setState(() {
          isLoading = false;
          address = res['regeocode']['formatted_address'];
        });
      } else {
        print('逆地址解析失败');
      }
    } catch (e) {
      print(e);
      setState(() {
        isLoading = false;
        address = '获取位置失败';
      });
    }
  }

  /// 查询附近社区
  Future<void> queryNearbyCommunities(double longitude, double latitude) async {
    String url =
        '$baseUrl/place/around?key=$key&location=$longitude,$latitude&radius=500&types=住宅小区';
    try {
      var response = await http.get(url, returnFullResponse: true);
      setState(() {
        nearbyCommunities = response['pois'];
      });
    } catch (e) {
      print('查询过程中出现错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(title: '选择社区'),
      body: Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.all(16),
            child: Text(
              '当前地点',
              style: TextStyle(fontSize: 12, color: AppColors.textSecondary),
            ),
          ),
          Row(
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                color: AppColors.white,
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        '$address',
                        style: TextStyle(
                          color:
                              isLoading
                                  ? AppColors.textSecondary
                                  : AppColors.black,
                        ),
                      ),
                    ),
                    SizedBox(width: 12),
                    GestureDetector(
                      onTap: () async {
                        doAsyncInit();
                      },
                      child: Row(
                        children: [
                          Icon(Icons.location_on, color: AppColors.primary),
                          Text(
                            '重新定位',
                            style: TextStyle(color: AppColors.primary),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.all(16),
            child: Text(
              '附近社区',
              style: TextStyle(fontSize: 12, color: AppColors.textSecondary),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: nearbyCommunities.length,
              itemBuilder: (context, index) {
                return Container(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  color: AppColors.white,
                  margin: EdgeInsets.only(bottom: 1),
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(
                        context,
                        '/addHouse',
                        arguments: {'name': nearbyCommunities[index]['name']},
                      );
                    },
                    child: Row(
                      children: [Text(nearbyCommunities[index]['name'])],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
